<template>
  <div class="login-container">
    <div class="login-left">
      <div class="affix">
        <span>Vue3+vite+Ts+Element-Plus</span>
        <el-button type="primary" @click="onGitee" size="small">Git</el-button>
      </div>
      <div class="form">
        <span>Sign In</span>
        <el-form ref="loginFormRef" :rules="rules" :model="loginForm">
          <el-form-item prop="username">
            <el-input v-model.trim="loginForm.username" placeholder="Account" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              show-password
              v-model.trim="loginForm.password"
              placeholder="Password"
            />
          </el-form-item>
          <el-form-item>
            <el-switch v-model="isRemember" active-text="Remember me" />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="onLogin(loginFormRef)"
              :loading="loading"
              >Sign In</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="login-right">
      <div class="inner">
        <span class="animated rubberBand">"A_xin Admin"</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { Login } from "@/http/interface";
import { loginApi } from "@/http/modules/login";
import { ElMessage, ElNotification } from "element-plus";
import { useRouter } from "vue-router";
import { getTimeState } from "@/utils/utils";
import { GlobalStore } from "@/stores";
import { MenuStore } from "@/stores/modules/menu";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import type { FormInstance, FormRules } from "element-plus";
import { GITEE_URL } from "@/config/config";

const globalStore = GlobalStore();
const menuStore = MenuStore();
const router = useRouter();
// form表单规则校验
const loginFormRef = ref();
const loginForm = reactive<Login.ReqLoginForm>({ username: "", password: "" });
const rules = reactive<FormRules>({
  username: [{ required: true, message: "Please input Account" }],
  password: [{ required: true, message: "Please input Password" }],
});
const loading = ref(false);
const isRemember = ref(false);

onMounted(() => {
  // 监听enter事件（调用登录）
  document.addEventListener("keydown", onKeyDown);
});

const onKeyDown = (e: any) => {
  if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
    if (loading.value) return;
    onLogin(loginFormRef.value);
  }
};

// 登录
const onLogin = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      const { data } = await loginApi(loginForm);
      if (data.status !== 200) return ElMessage.error(data.msg);
      globalStore.setToken(data.token);
      // 添加动态路由
      await initDynamicRouter();

      // 清空 tabs、keepAlive 保留的数据
      globalStore.closeMultipleTab();
      menuStore.setKeepAliveName();

      router.push("layout");
      ElNotification({
        title: getTimeState(),
        message: data.userInfo.username,
        type: "success",
        duration: 3000,
      });
    } finally {
      loading.value = false;
    }
  });
};

const onGitee = () => {
  window.open(GITEE_URL);
};
</script>

<style lang="scss" scoped>
@import "index.scss";
</style>
